<template>
  <div>
    <el-form label-position="top" label-width="80px" :model="form" ref="form" :rules="rules">
      <el-form-item label="试题题干" prop="stem">
        <!-- <el-input
            v-model="form.stem"
            type="textarea"
            autosize
          ></el-input> -->

        <Editor :stem="form.stem" @changStem="changStem" ref="Editor" />
      </el-form-item>

      <el-form-item label="答案选项" prop="option">
        <el-form-item :label="'[' + list.name + ']'" v-for="list in form.option" :key="list.name">
          <el-input v-model="list.content"></el-input>
        </el-form-item>
        <el-button type="primary" size="mini" :style="{
          backgroundColor: theme,
          borderColor: theme,
          fontWeight: 'bold'
        }" @click="handleAddAns()">添加选项
        </el-button>

        <el-button size="mini" v-show="form.option && form.option.length > 4" @click="handleDelAns()">
          删除</el-button>
      </el-form-item>
      <el-form-item label="正确答案" prop="answer">
        <el-checkbox-group v-model="form.answer" size="mini">
          <el-checkbox :label="item.name" border v-for="(item, index) in form.option" :key="index"></el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="答案解析" prop="explain">
        <el-input type="textarea" autosize v-model="form.explain"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :style="{
          backgroundColor: theme,
          borderColor: theme,
          fontWeight: 'bold'
        }" @click="submitForm" v-loading.fullscreen.lock="fullscreenLoading">保存</el-button>
        <el-button @click="$router.push({ name: 'Question' })">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import Editor from "@/views/vadmin/question/components/editor";
import { addQuestion, updateQuestion } from "@/api/vadmin/question/index";
import { mapGetters, mapState } from "vuex";
import variables from "@/assets/styles/variables.scss";
export default {
  name: "newKnowledge",
  components: { Editor },
  props: ["data"],

  data() {
    return {
      // 遮罩层
      fullscreenLoading: false,
      form: {
        answer: [],
        option: [
          { name: "A", content: "", is_right: false },
          { name: "B", content: "", is_right: false },
          { name: "C", content: "", is_right: false },
          { name: "D", content: "", is_right: false },
        ],
        explain: null,
        type_name: "单选题",
        type: "3",
        stem: null,
        score: null,
        sort: 1,

      },
      answer: "",
      // 表单校验
      rules: {
        stem: [
          { required: true, message: "试题题干不能为空", trigger: "blur" },
        ],
        answer: [
          { required: true, message: "正确答案不能为空", trigger: "blur" },
        ],
        option: [{ required: true, message: "选项不能为空", trigger: "blur" }],
        // explain: [
        //   { required: true, message: "答案解析不能为空", trigger: "blur" },
        // ],
      },
    };
  },

  computed: {
    ...mapState(["settings"]),
    variables() {
      return variables;
    },
    theme() {
      return this.$store.state.settings.theme;
    },
  },

  watch: {
    data: {
      handler: function (newValue) {
        this.form = newValue;
      },
      deep: true,
    },
    'form.answer': {
      handler: function (newValue) {

        this.form.answer = newValue;
        // console.log("修改了答案", this.form.answer)
      },
      deep: true,
    },
  },

  created() {
    // console.log("多选22", this.form);
  },

  mounted() { },

  methods: {
    changStem(val) {
      this.form.stem = val;
    },
    reset() {
      this.form = {
        answer: [],
        option: [
          { name: "A", content: "", is_right: false },
          { name: "B", content: "", is_right: false },
          { name: "C", content: "", is_right: false },
          { name: "D", content: "", is_right: false },
        ],
        explain: null,
        stem: null,
        score: null,
        knowledge: "",
        course: "",
        sort: 1,

      };
    },
    /** 提交按钮 */
    submitForm: function () {
      this.form.stem = this.$refs["Editor"].getVal();
      this.$refs["form"].validate((valid) => {
        // console.log("题目", this.form);
        this.form.score = 1; //默认每题1分
        this.form.type = 2; //设置题型
        delete this.form["is_right"];

        this.form.option = this.form.option.map((item) => {

          if (this.form.answer.includes(item.name)) {
            item.is_right = true;
          } else {
            item.is_right = false;
          }
          return item;
        });

        if (this.form.knowledge == "") {
          this.msgError("知识点选项不可为空");
        } else if (this.form.course == "") {
          this.msgError("请选择课程");
        } else {
          if (valid) {
            this.fullscreenLoading = true;
            if (this.form.id != undefined) {
              updateQuestion(this.form).then((response) => {
                this.fullscreenLoading = false;
                this.msgSuccess("修改成功");
              });
            } else {
              addQuestion(this.form).then((response) => {
                this.msgSuccess("新增成功");
                this.fullscreenLoading = false;
                this.reset();
              });
            }
          }
        }
      });
    },
    /** 新增选项 */
    handleAddAns() {
      //使用Unicode编码，首先获得E的编码，然后增加已有编号的长度，再转换为字母
      var options = String.fromCharCode(
        "E".charCodeAt(0) + this.form.option.length - 4
      );
      this.form.option.push({ name: options, content: "" });
    },
    handleDelAns() {
      this.form.option.splice(this.form.option.length - 1, 1);
    },
  },
};
</script>

